define(['utils'], function(util) {
    const socket = util.socket;
    const Socket = new util.Class();

    Socket.include({
        /**
         * 组装请求格式
         * @param Command
         * @param CommandType
         * @param Body
         * @returns {{Command: *, CommandType: *, Body: *, token: string}}
         */
        createSocketOption (Command, CommandType, Body) {
            const token = util.getStorage('auth_token');
            return {
                Command,
                CommandType,
                token,
                Body
            };
        },

        /**
         * socket business
         * @param command
         * @param data
         * @returns {Promise<unknown>}
         */
        business (command, data = {}) {
            const socketOpt = this.createSocketOption(command, 'Business', { data });

            socket.emit('Business', JSON.stringify(socketOpt));

            return new Promise((resolve) => {
                socket.on('Business',  (data) => {
                    // ~~ 取整
                    if (~~command === 56) {
                        // 获取证据
                        if (~~data.code === 1) {
                            resolve(data)
                        } else if (~~data.code === 2) {
                            JPop.alert({ msg: '无报警附件', type:'info' })
                        }
                    } else {
                        // 查岗，督办，公告 下发成功即可
                        if (data.Msg) {
                            JPop.alert({ msg: data.Msg, type: 'success' })
                        }
                        resolve(data)
                    }
                });
            })
        },

        /**
         * socket track
         * @param command
         * @param data
         * @returns {Promise<unknown>}
         */
        track (command, data = {}) {
            const userId = util.getStorage('userId');
            const socketOpt = this.createSocketOption(command, 'track', { data, userId });

            socket.emit('track', socketOpt);

            return new Promise((resolve) => {
                socket.on('trackReal',  resolve);
            })
        },


        /**
         * socket io
         * @param type
         * @param name
         * @param command
         * @param data
         * @returns {Promise<unknown>}
         */
        io (type, name, command, data = {}) {
            const socketOpt = this.createSocketOption(command, type, { data });

            socket.emit(type, socketOpt);

            return new Promise((resolve) => {
                socket.on(name,  resolve);
            })

        }
    });

    return new Socket()
});
